#include <iostream>
#include <sys/socket.h> // socket
#include <netinet/in.h> // local
#include <arpa/inet.h> // htons inet_addr
#include <cstring> // memset 
#include <unistd.h> // close fork
#include <thread>

void handle_client(int socket)
{
    char buffer[1024];
    std::thread::id thread_id = std::this_thread::get_id();
    while (true)
    {
        int n = read(socket, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << thread_id << "client Say# " << buffer << std::endl;
            int m = write(socket, buffer, n);
            if (m < 0)
            {
                std::cout << "write fail" << std::endl;
                return;
            }
        }
        else
        {
            std::cout << "read fail" << std::endl;
            return;
        }
    }
    
}

int main(int argc, char *argv[])
{
    if (argc != 2) 
    {
        std::cout << "Usage: ./TcpServer port" << std::endl;
        return 1;
    }

    uint16_t serverport = std::stoi(argv[1]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket fail" << std::endl;
        return 1;
    }

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = INADDR_ANY;

    int n = bind(sockfd, (struct sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        std::cout << "bind fail" << std::endl;
        close(sockfd);
        return 1;
    }

    n = listen(sockfd, 5);
    if (n < 0)
    {
        std::cout << "listen fail" << std::endl;
        close(sockfd);
        return 1;
    }

    std::cout << "TCP Server is running on " << serverport << "..." << std::endl;

    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    while (true)
    {
        int clientsocket = accept(sockfd, (struct sockaddr*)&client, &len);
        if (clientsocket < 0)
        {
            std::cout << "accept fail" << std::endl;
            close(sockfd);
            return 1;
        }
        
        std::thread(handle_client, clientsocket).detach();
    }
    
    close(sockfd);

    return 0;
}